package com.jcfk.eam.service.csm;


import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.eam.dao.csm.CsmLedgerManageDao;
import com.jcfk.eam.domain.dto.csm.CsmLedgerManageDTO;
import com.jcfk.eam.domain.po.csm.CsmLedgerManage;
import com.jcfk.eam.domain.query.csm.CsmLedgerManageQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

/**
 * 消耗品台账管理
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2024-11-04
 */
@Service
public class CsmLedgerManageService extends BaseService<CsmLedgerManageDao, CsmLedgerManage> {

    /**
     * CsmLedgerManage分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<CsmLedgerManageDTO> queryByPage(DataPage<CsmLedgerManageDTO> page, CsmLedgerManageQuery query) {
        // 分页查询
        query.setMaterialId(StringUtils.isEmpty(query.getMaterialId()) ? query.getMaterialId() : query.getMaterialId() + "%");
        query.setMaterialId(StringUtils.isEmpty(query.getMaterialCode()) ? query.getMaterialCode() : query.getMaterialCode() + "%");
        query.setMaterialId(StringUtils.isEmpty(query.getMaterialGroupName()) ? query.getMaterialGroupName() : query.getMaterialGroupName() + "%");
        query.setMaterialId(StringUtils.isEmpty(query.getEquipCode()) ? query.getEquipCode() : query.getEquipCode() + "%");
        page = this.baseMapper.queryByPage(page, query);

        QueryWrapper<CsmLedgerManage> qw = new QueryWrapper<>();
        qw.lambda().ne(CsmLedgerManage::getPid, '0');
        // 查询数据
        List<CsmLedgerManageDTO> list = baseMapper.getchilds(query);

        List<CsmLedgerManageDTO> dtos = new ArrayList<>();
        dtos.addAll(page.getRecords());
        dtos.addAll(convertList(list, CsmLedgerManageDTO.class));


        Map<String, List<CsmLedgerManageDTO>> parentChildMap = new HashMap<>();
        // 将节点按照父节点进行分组
        for (CsmLedgerManageDTO node : dtos) {
            String parentTypeId = node.getPid();
            parentChildMap.computeIfAbsent(parentTypeId, k -> new ArrayList<>()).add(node);
        }
        List<CsmLedgerManageDTO> tree = new ArrayList<>();
        // 递归组装树结构
        buildTree(tree, parentChildMap, "0");

        page.setRecords(tree);
        return page;
    }


    private static void buildTree(List<CsmLedgerManageDTO> tree, Map<String, List<CsmLedgerManageDTO>> parentChildMap, String parentTypeId) {
        List<CsmLedgerManageDTO> children = parentChildMap.get(parentTypeId);
        if (children != null) {
            for (CsmLedgerManageDTO child : children) {
                List<CsmLedgerManageDTO> grandchildren = parentChildMap.get(child.getId());
                if (grandchildren != null) {
                    buildTree(child.getNodes(), parentChildMap, child.getId());
                }
                tree.add(child);
            }
        }
    }

    /**
     * 判断CsmLedgerManage是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(CsmLedgerManageDTO dto) {
        QueryWrapper<CsmLedgerManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        return RetResult.ok();
    }

    /**
     * 插入消耗品台账管理
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(CsmLedgerManageDTO dto) {

        // 保存
        CsmLedgerManage item = new CsmLedgerManage();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        super.save(item);
    }

    /**
     * 更新消耗品台账管理
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(CsmLedgerManageDTO dto) {

        // 保存
        CsmLedgerManage item = new CsmLedgerManage();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);
    }

    /**
     * 根据批量主键删除消耗品台账管理(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(CsmLedgerManageDTO dto) {

        CsmLedgerManage item = new CsmLedgerManage();

        this.setDefaultValue(item);
        item.setDeleted(1);

        QueryWrapper<CsmLedgerManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(CsmLedgerManage item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setDeleted(0);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());

    }

    /**
     * 根据主键获取消耗品台账管理信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public CsmLedgerManageDTO get(String id) {
        // 查询数据
        CsmLedgerManage item = this.baseMapper.selectById(id);
        CsmLedgerManageDTO dto = new CsmLedgerManageDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }


    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<CsmLedgerManageDTO>
     */
    public List<CsmLedgerManageDTO> getList(CsmLedgerManageQuery query) {
        // 查询条件
        QueryWrapper<CsmLedgerManage> qw = new QueryWrapper<>();
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getMaterialId()), CsmLedgerManage::getMaterialId, query.getMaterialId());
        // 查询数据
        List<CsmLedgerManage> list = super.list(qw);

        return convertList(list, CsmLedgerManageDTO.class);
    }

    /**
     * 根据主键获取消耗品台账管理信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteItem(String id) {
        CsmLedgerManage item = getById(id);
        this.setDefaultValue(item);
        item.setDeleted(1);

        this.updateById(item);
    }
}

